package com.server.llh.llhserverwork.activity.base;

import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.card.bleNfcBase.FinancialCard;
import com.card.bleNfcBase.SZTCard;
import com.dk.bleNfc.BleManager.BleManager;
import com.dk.bleNfc.BleManager.Scanner;
import com.dk.bleNfc.BleManager.ScannerCallback;
import com.dk.bleNfc.BleNfcDeviceService;
import com.dk.bleNfc.DeviceManager.BleNfcDevice;
import com.dk.bleNfc.DeviceManager.ComByteManager;
import com.dk.bleNfc.DeviceManager.DeviceManager;
import com.dk.bleNfc.DeviceManager.DeviceManagerCallback;
import com.dk.bleNfc.Exception.CardNoResponseException;
import com.dk.bleNfc.Exception.DeviceNoResponseException;
import com.dk.bleNfc.Tool.CardSubChackUtil;
import com.dk.bleNfc.Tool.StringTool;
import com.dk.bleNfc.card.CpuCard;
import com.dk.bleNfc.card.FeliCa;
import com.dk.bleNfc.card.Iso14443bCard;
import com.dk.bleNfc.card.Iso15693Card;
import com.dk.bleNfc.card.Mifare;
import com.dk.bleNfc.card.Ntag21x;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.NetRequestManager;

import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.my.LoginActivity;
import com.server.llh.llhserverwork.app.LelaohuirelativesApp;
import com.server.llh.llhserverwork.bean.Constants;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import butterknife.ButterKnife;

/**
 * Created by ZTF on 2017-06-05.
 */

public class LlhWelcomeActivity extends LlhBaseActivity {

    BleNfcDeviceService mBleNfcDeviceService;
    private BleNfcDevice bleNfcDevice;
    private Scanner mScanner;


    private StringBuffer msgBuffer;
    private BluetoothDevice mNearestBle = null;
    private Lock mNearestBleLock = new ReentrantLock();// 锁对象
    private int lastRssi = -100;
    private CharSequence[] items = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        msgBuffer = new StringBuffer();
        LelaohuirelativesApp.addActivity(LlhWelcomeActivity.this);
        NfcManager manager = (NfcManager) getApplicationContext().getSystemService(Context.NFC_SERVICE);
        NfcAdapter adapter = manager.getDefaultAdapter();
        if (adapter != null && adapter.isEnabled()) {
            // adapter存在，能启用
            Log.d("TAG","adapter存在，能启用");
            Intent intent=new Intent(getApplicationContext(), LoginActivity.class);
            intent.putExtra("succStatus","-1");
            startActivity(intent);

        }else{
            Log.d("TAG","adapter 不存在，能启用");
            //ble_nfc服务初始化
            Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
            bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        }
    }
    // Code to manage Service lifecycle.开启服务，连接服务
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            BleNfcDeviceService mBleNfcDeviceService = ((BleNfcDeviceService.LocalBinder) service).getService();
            bleNfcDevice = mBleNfcDeviceService.bleNfcDevice;
            mScanner = mBleNfcDeviceService.scanner;
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
            mBleNfcDeviceService.setScannerCallback(scannerCallback);
            //开始搜索设备
            searchNearestBleDevice();
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBleNfcDeviceService = null;
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        if (mBleNfcDeviceService != null) {
            mBleNfcDeviceService.setScannerCallback(scannerCallback);
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
        }
//        Handler handler=new Handler();
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Intent intent=new Intent(getApplicationContext(), LoginActivity.class);
//                startActivity(intent);
//            }
//        },1000);
    }


    //设备操作类回调
    private DeviceManagerCallback deviceManagerCallback = new DeviceManagerCallback() {
        @Override
        public void onReceiveConnectBtDevice(boolean blnIsConnectSuc) {
            super.onReceiveConnectBtDevice(blnIsConnectSuc);
            if (blnIsConnectSuc) {
                System.out.println("Activity设备连接成功");
                msgBuffer.delete(0, msgBuffer.length());
                msgBuffer.append("设备连接成功!\r\n");
                if (mNearestBle != null) {
                    msgBuffer.append("设备名称：").append(bleNfcDevice.getDeviceName()).append("\r\n");
                }
                msgBuffer.append("信号强度：").append(lastRssi).append("dB\r\n");
                msgBuffer.append("SDK版本：" + BleNfcDevice.SDK_VERSIONS + "\r\n");

                //连接上后延时500ms后再开始发指令
                try {
                    Thread.sleep(500L);
                    handler.sendEmptyMessage(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else{
                Intent intent=new Intent(getApplicationContext(), LoginActivity.class);
                intent.putExtra("succStatus","1");
                startActivity(intent);
            }
        }

        @Override
        public void onReceiveDisConnectDevice(boolean blnIsDisConnectDevice) {
            super.onReceiveDisConnectDevice(blnIsDisConnectDevice);
            System.out.println("Activity设备断开链接");
            msgBuffer.delete(0, msgBuffer.length());
            msgBuffer.append("设备断开链接!");
//            if (mServiceConnection!=null){
//                unbindService(mServiceConnection);
//            }
            handler.sendEmptyMessage(0);
        }

        @Override
        public void onReceiveConnectionStatus(boolean blnIsConnection) {
            super.onReceiveConnectionStatus(blnIsConnection);
            System.out.println("Activity设备链接状态回调");
        }

        @Override
        public void onReceiveInitCiphy(boolean blnIsInitSuc) {
            super.onReceiveInitCiphy(blnIsInitSuc);
        }

        @Override
        public void onReceiveDeviceAuth(byte[] authData) {
            super.onReceiveDeviceAuth(authData);
        }

        @Override
        //寻到卡片回调
        public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
            super.onReceiveRfnSearchCard(blnIsSus, cardType, bytCardSn, bytCarATS);
            if (!blnIsSus || cardType == BleNfcDevice.CARD_TYPE_NO_DEFINE) {
                return;
            }

            System.out.println("Activity接收到激活卡片回调：UID->" + StringTool.byteHexToSting(bytCardSn) + " ATS->" + StringTool.byteHexToSting(bytCarATS));

            final int cardTypeTemp = cardType;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean isReadWriteCardSuc;
                    try {
                        if (bleNfcDevice.isAutoSearchCard()) {
                            //如果是自动寻卡的，寻到卡后，先关闭自动寻卡
                            bleNfcDevice.stoptAutoSearchCard();
                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);

                            //读卡结束，重新打开自动寻卡
                            startAutoSearchCard();
                        }
                        else {
                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);

                            //如果不是自动寻卡，读卡结束,关闭天线
                            bleNfcDevice.closeRf();
                        }

                        //打开蜂鸣器提示读卡完成
                        if (isReadWriteCardSuc) {
                            bleNfcDevice.openBeep(50, 50, 3);  //读写卡成功快响3声
                        }
                        else {
                            bleNfcDevice.openBeep(100, 100, 2); //读写卡失败慢响2声
                        }
                    } catch (DeviceNoResponseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        public void onReceiveRfmSentApduCmd(byte[] bytApduRtnData) {
            super.onReceiveRfmSentApduCmd(bytApduRtnData);

            System.out.println("Activity接收到APDU回调：" + StringTool.byteHexToSting(bytApduRtnData));
        }

        @Override
        public void onReceiveRfmClose(boolean blnIsCloseSuc) {
            super.onReceiveRfmClose(blnIsCloseSuc);
        }

        @Override
        //按键返回回调
        public void onReceiveButtonEnter(byte keyValue) {
            if (keyValue == DeviceManager.BUTTON_VALUE_SHORT_ENTER) { //按键短按
                System.out.println("Activity接收到按键短按回调");
                msgBuffer.append("按键短按\r\n");
                handler.sendEmptyMessage(0);
            }
            else if (keyValue == DeviceManager.BUTTON_VALUE_LONG_ENTER) { //按键长按
                System.out.println("Activity接收到按键长按回调");
                msgBuffer.append("按键长按\r\n");
                handler.sendEmptyMessage(0);
            }
        }
    };


    //搜索最近的设备并连接
    private void searchNearestBleDevice() {
        msgBuffer.delete(0, msgBuffer.length());
        msgBuffer.append("正在搜索设备...");
        handler.sendEmptyMessage(0);
        if (!mScanner.isScanning() && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        mScanner.startScan(0);
                        mNearestBleLock.lock();
                        try {
                            mNearestBle = null;
                        }finally {
                            mNearestBleLock.unlock();
                        }
                        lastRssi = -100;

                        int searchCnt = 0;
                        while ((mNearestBle == null)
                                && (searchCnt < 10000)
                                && (mScanner.isScanning())
                                && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
                            searchCnt++;
                            try {
                                Thread.sleep(1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        if (mScanner.isScanning() && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mScanner.stopScan();
                            mNearestBleLock.lock();
                            try {
                                if (mNearestBle != null) {
                                    mScanner.stopScan();
                                    msgBuffer.delete(0, msgBuffer.length());
                                    msgBuffer.append("正在连接设备...");
                                    handler.sendEmptyMessage(0);
                                    bleNfcDevice.requestConnectBleDevice(mNearestBle.getAddress());
                                } else {
                                    msgBuffer.delete(0, msgBuffer.length());
                                    msgBuffer.append("未找到设备！");
                                    handler.sendEmptyMessage(0);
                                }
                            }finally {
                                mNearestBleLock.unlock();
                            }
                        } else {
                            mScanner.stopScan();
                        }
                    }
                }
            }).start();
        }
    }
    //Scanner 回调
    private ScannerCallback scannerCallback = new ScannerCallback() {
        @Override
        public void onReceiveScanDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
            super.onReceiveScanDevice(device, rssi, scanRecord);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //StringTool.byteHexToSting(scanRecord.getBytes())
                System.out.println("Activity搜到设备：" + device.getName()
                        + " 信号强度：" + rssi
                        + " scanRecord：" + StringTool.byteHexToSting(scanRecord));
            }
            //搜索蓝牙设备并记录信号强度最强的设备
            if ( (scanRecord != null) && (StringTool.byteHexToSting(scanRecord).contains("017f5450"))) {  //从广播数据中过滤掉其它蓝牙设备
                msgBuffer.append("搜到设备：").append(device.getName()).append(" 信号强度：").append(rssi).append("\r\n");
                handler.sendEmptyMessage(0);
                if (mNearestBle != null) {
                    if (rssi > lastRssi) {
                        mNearestBleLock.lock();
                        try {
                            mNearestBle = device;
                        }finally {
                            mNearestBleLock.unlock();
                        }
                    }
                }
                else {
                    mNearestBleLock.lock();
                    try {
                        mNearestBle = device;
                    }finally {
                        mNearestBleLock.unlock();
                    }
                    lastRssi = rssi;
                }
            }
        }

        @Override
        public void onScanDeviceStopped() {
            super.onScanDeviceStopped();
        }
    };

    @Override
    public void showProgress() {

    }

    @Override
    protected INetRequestManager getRequestManager() {
        return NetRequestManager.getInstance();
    }

    @Override
    public void hideProgress() {

    }

    @Override
    protected int getlayout() {
        return R.layout.activity_welcome;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {

    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            msgText.setText(msgBuffer);
            if ( (bleNfcDevice.isConnection() == BleManager.STATE_CONNECTED) || ((bleNfcDevice.isConnection() == BleManager.STATE_CONNECTING)) ) {
//                Toast.makeText(getApplicationContext(),"断开连接",Toast.LENGTH_LONG).show();
            }
            else {
//                Toast.makeText(getApplicationContext(),"搜索设备",Toast.LENGTH_LONG).show();
             }
            switch (msg.what) {
                case 0:

                    Log.d("TAG","链接失败");
                    break;
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                byte versions = bleNfcDevice.getDeviceVersions();
                                msgBuffer.append("设备版本:").append(String.format("%02x", versions)).append("\r\n");
                                handler.sendEmptyMessage(0);
                                double voltage = bleNfcDevice.getDeviceBatteryVoltage();
                                msgBuffer.append("设备电池电压:").append(String.format("%.2f", voltage)).append("\r\n");
                                if (voltage < 3.61) {
                                    msgBuffer.append("设备电池电量低，请及时充电！");
                                } else {
                                    msgBuffer.append("设备电池电量充足！");
                                }
                                handler.sendEmptyMessage(0);
                                boolean isSuc = bleNfcDevice.androidFastParams(true);
                                if (isSuc) {
                                    msgBuffer.append("\r\n蓝牙快速传输参数设置成功!");
                                }
                                else {
                                    msgBuffer.append("\n不支持快速传输参数设置!");
                                }
                                handler.sendEmptyMessage(0);

                                msgBuffer.append("\n开启自动寻卡...\r\n");
                                handler.sendEmptyMessage(0);
                                Intent intent=new Intent(getApplicationContext(), LoginActivity.class);
                                intent.putExtra("succStatus","0");
                                startActivity(intent);
                                //开始自动寻卡
                                startAutoSearchCard();
                            } catch (DeviceNoResponseException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;

                case 4:   //读写进度条

                    break;
                case 7:  //搜索设备列表

                    break;
            }
        }
    };
    //开始自动寻卡
    private boolean startAutoSearchCard() throws DeviceNoResponseException {
        //打开自动寻卡，200ms间隔，寻M1/UL卡
        boolean isSuc = false;
        int falseCnt = 0;
        do {
            isSuc = bleNfcDevice.startAutoSearchCard((byte) 20, ComByteManager.ISO14443_P4);
        }while (!isSuc && (falseCnt++ < 10));
        if (!isSuc){
            //msgBuffer.delete(0, msgBuffer.length());
            msgBuffer.append("不支持自动寻卡！\r\n");
            handler.sendEmptyMessage(0);
        }
        return isSuc;
    }
    //读写卡Demo
    private boolean readWriteCardDemo(int cardType) {
        switch (cardType) {
            case DeviceManager.CARD_TYPE_ISO4443_B:  //寻到 B cpu卡
                final Iso14443bCard iso14443bCard = (Iso14443bCard) bleNfcDevice.getCard();
                if (iso14443bCard != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到ISO14443-B卡->UID:(身份证发送0036000008指令获取UID)\r\n");
                    handler.sendEmptyMessage(0);
                    //获取身份证UID的指令流
                    final byte[][] sfzCmdBytes = {
                            {0x00, (byte) 0x84, 0x00, 0x00, 0x08},
                            {0x00, 0x36, 0x00, 0x00, 0x08},
                    };
                    System.out.println("发送指令流");
                    for (byte[] aBytes : sfzCmdBytes) {
                        try {
                            msgBuffer.append("发送：").append(StringTool.byteHexToSting(aBytes)).append("\r\n");
                            handler.sendEmptyMessage(0);
                            byte returnBytes[] = iso14443bCard.transceive(aBytes);
                            msgBuffer.append("返回：").append(StringTool.byteHexToSting(returnBytes)).append("\r\n");
                            handler.sendEmptyMessage(0);
                        } catch (CardNoResponseException e) {
                            e.printStackTrace();
                            return false;
                        }
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ISO4443_A:   //寻到A CPU卡
                final CpuCard cpuCard = (CpuCard) bleNfcDevice.getCard();
                if (cpuCard != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到CPU卡->UID:").append(cpuCard.uidToString()).append("\r\n");
                    handler.sendEmptyMessage(0);
                    try{
                        //选择深圳通主文件
                        byte[] bytApduRtnData = cpuCard.transceive(SZTCard.getSelectMainFileCmdByte());
                        if (bytApduRtnData.length <= 2) {
                            System.out.println("不是深圳通卡，当成银行卡处理！");
                            //选择储蓄卡交易文件
                            String cpuCardType;
                            bytApduRtnData = cpuCard.transceive(FinancialCard.getSelectDepositCardPayFileCmdBytes());
                            if (bytApduRtnData.length <= 2) {
                                System.out.println("不是储蓄卡，当成借记卡处理！");
                                //选择借记卡交易文件
                                bytApduRtnData = cpuCard.transceive(FinancialCard.getSelectDebitCardPayFileCmdBytes());
                                if (bytApduRtnData.length <= 2) {
                                    msgBuffer.append("未知CPU卡！");
                                    handler.sendEmptyMessage(0);
                                    return false;
                                }
                                else {
                                    cpuCardType = "储蓄卡";
                                }
                            }
                            else {
                                cpuCardType = "借记卡";
                            }

                            //发送获取银行卡卡号指令
                            bytApduRtnData = cpuCard.transceive(FinancialCard.getCardNumberCmdBytes());
                            //提取银行卡卡号
                            String cardNumberString = FinancialCard.extractCardNumberFromeRturnBytes(bytApduRtnData);
                            if (cardNumberString == null) {
                                msgBuffer.append("未知CPU卡！");
                                handler.sendEmptyMessage(0);
                                return false;
                            } else {
                                msgBuffer.append(cpuCardType).append("卡号：").append(cardNumberString);
                                handler.sendEmptyMessage(0);

                                //读交易记录
                                System.out.println("发送APDU指令-读10条交易记录");
                                for (int i = 1; i <= 10; i++) {
                                    bytApduRtnData = cpuCard.transceive(FinancialCard.getTradingRecordCmdBytes((byte) i));
                                    msgBuffer.append(FinancialCard.extractTradingRecordFromeRturnBytes(bytApduRtnData));
                                    handler.sendEmptyMessage(0);
                                }
                            }
                        }
                        else {  //深圳通处理流程
                            bytApduRtnData = cpuCard.transceive(SZTCard.getBalanceCmdByte());
                            if (SZTCard.getBalance(bytApduRtnData) == null) {
                                msgBuffer.append("未知CPU卡！");
                                handler.sendEmptyMessage(0);
                                System.out.println("未知CPU卡！");
                                return false;
                            }
                            else {
                                msgBuffer.append("深圳通余额：").append(SZTCard.getBalance(bytApduRtnData));
                                handler.sendEmptyMessage(0);
                                System.out.println("余额：" + SZTCard.getBalance(bytApduRtnData));
                                //读交易记录
                                System.out.println("发送APDU指令-读10条交易记录");
                                for (int i = 1; i <= 10; i++) {
                                    bytApduRtnData = cpuCard.transceive(SZTCard.getTradeCmdByte((byte) i));
                                    msgBuffer.append("\r\n").append(SZTCard.getTrade(bytApduRtnData));
                                    handler.sendEmptyMessage(0);
                                }
                            }
                        }
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_FELICA:  //寻到FeliCa
                FeliCa feliCa = (FeliCa) bleNfcDevice.getCard();
                if (feliCa != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("读取服务008b中数据块0000的数据：\r\n");
                    handler.sendEmptyMessage(0);
                    byte[] pServiceList = {(byte) 0x8b, 0x00};
                    byte[] pBlockList = {0x00, 0x00, 0x00};
                    try {
                        byte[] pBlockData = feliCa.read((byte) 1, pServiceList, (byte) 1, pBlockList);
                        msgBuffer.append(StringTool.byteHexToSting(pBlockData)).append("\r\n");
                        handler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ULTRALIGHT: //寻到Ultralight卡


                final Ntag21x ntag21x = (Ntag21x) bleNfcDevice.getCard();
                if (ntag21x != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到Ultralight卡 ->UID:").append(ntag21x.uidToString()).append("\r\n");
                    handler.sendEmptyMessage(0);
                    try {
                        //读写单个块Demo
                        msgBuffer.append("开始读取块0数据：\r\n");
                        handler.sendEmptyMessage(0);
                        byte[] readTempBytes = ntag21x.read((byte) 0);
                        msgBuffer.append("返回：").append(StringTool.byteHexToSting(readTempBytes)).append("\r\n");
                        handler.sendEmptyMessage(0);

                        byte[] writeBytes = new byte[888];
                        Arrays.fill(writeBytes, (byte) 0x30);
                        msgBuffer.append("开始写888个字节数据：0x30").append("\r\n");
                        handler.sendEmptyMessage(0);
                        boolean isSuc = ntag21x.longWriteWithScheduleCallback((byte) 4, writeBytes, new Ntag21x.onReceiveScheduleListener() {
                            @Override
                            public void onReceiveSchedule(int rate) {
//                                showReadWriteDialog("正在写入数据", rate);
                            }
                        });
                        if (isSuc) {
                            msgBuffer.append("写数据成功！").append("\r\n");
                            handler.sendEmptyMessage(0);
                            msgBuffer.append("开始读888个字节数据").append("\r\n");
                            handler.sendEmptyMessage(0);
                            readTempBytes = ntag21x.longReadWithScheduleCallback((byte) 4, (byte) (888 / 4), new Ntag21x.onReceiveScheduleListener() {
                                @Override
                                public void onReceiveSchedule(int rate) {
//                                    showReadWriteDialog("正在读取数据", rate);
                                }
                            });
                            msgBuffer.append("读取成功：\r\n").append(StringTool.byteHexToSting(readTempBytes)).append("\r\n");
//                            showReadWriteDialog("正在读取数据", 100);
                        }
                        else {
                            msgBuffer.append("写数据失败！").append("\r\n");
//                            showReadWriteDialog("正在读取数据", 0);
                        }


                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        msgBuffer.append(e.getMessage()).append("\r\n");
//                        showReadWriteDialog("正在写入数据", 0);
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_MIFARE:   //寻到Mifare卡
                final Mifare mifare = (Mifare) bleNfcDevice.getCard();
                if (mifare != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到Mifare卡->UID:").append(mifare.uidToString()).append("\r\n");
                    msgBuffer.append("开始验证第1块密码\r\n");
                    String cardData=mifare.uidToString();
                     cardData= CardSubChackUtil.toZheng(CardSubChackUtil.ReverseString(cardData)) +"";
                    System.out.println("ChackCardNo=="+cardData);
                    if (cardData!=null){
                        Intent intent = new Intent();
                        if ((new Long(cardData)).toString().length()<10){
                            intent.putExtra("cardNo", "0"+cardData + "");
                        }else{
                            intent.putExtra("cardNo", cardData + "");
                        }
//                        intent.putExtra("cardNo",cardData);
                        Log.d("cardId","cardData22=="+cardData);
                        intent.setAction(Constants.BroadCastAction.READ_CARD_NO);
                        sendBroadcast(intent);
                    }
                    handler.sendEmptyMessage(0);
                    byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
                    try {
                        boolean anth = mifare.authenticate((byte) 1, Mifare.MIFARE_KEY_TYPE_A, key);
                        if (anth) {
                            msgBuffer.append("验证密码成功\r\n");
                            msgBuffer.append("写00112233445566778899001122334455到块1\r\n");
                            handler.sendEmptyMessage(0);
                            boolean isSuc = mifare.write((byte)1, new byte[]{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55});
                            if (isSuc) {
                                msgBuffer.append("写成功！\r\n");
                                msgBuffer.append("读块1数据\r\n");
                                handler.sendEmptyMessage(0);
                                byte[] readDataBytes = mifare.read((byte) 1);
                                msgBuffer.append("块1数据:").append(StringTool.byteHexToSting(readDataBytes)).append("\r\n");
                                handler.sendEmptyMessage(0);
                            } else {
                                msgBuffer.append("写失败！\r\n");
                                handler.sendEmptyMessage(0);
                                return false;
                            }
                        }
                        else {
                            msgBuffer.append("验证密码失败\r\n");
                            handler.sendEmptyMessage(0);
                            return false;
                        }
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ISO15693: //寻到15693卡
                final Iso15693Card iso15693Card = (Iso15693Card) bleNfcDevice.getCard();
                if (iso15693Card != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到15693卡->UID:").append(iso15693Card.uidToString()).append("\r\n");
                    msgBuffer.append("读块0数据\r\n");
                    handler.sendEmptyMessage(0);
                    try {
                        //读写单个块Demo
                        msgBuffer.append("写数据01020304到块4").append("\r\n");
                        handler.sendEmptyMessage(0);
                        boolean isSuc = iso15693Card.write((byte)4, new byte[] {0x01, 0x02, 0x03, 0x04});
                        if (isSuc) {
                            msgBuffer.append("写数据成功！").append("\r\n");
                            handler.sendEmptyMessage(0);
                        }
                        else {
                            msgBuffer.append("写数据失败！").append("\r\n");
                            handler.sendEmptyMessage(0);
                        }
                        msgBuffer.append("读块4数据").append("\r\n");
                        handler.sendEmptyMessage(0);
                        byte[] bytes = iso15693Card.read((byte) 4);
                        msgBuffer.append("块4数据：").append(StringTool.byteHexToSting(bytes)).append("\r\n");
                        handler.sendEmptyMessage(0);
                        //读写多个块Demo
                        msgBuffer.append("写数据0102030405060708到块5、6").append("\r\n");
                        handler.sendEmptyMessage(0);
                        isSuc = iso15693Card.writeMultiple((byte)5, (byte)2, new byte[] {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
                        if (isSuc) {
                            msgBuffer.append("写数据成功！").append("\r\n");
                            handler.sendEmptyMessage(0);
                        }
                        else {
                            msgBuffer.append("写数据失败！").append("\r\n");
                            handler.sendEmptyMessage(0);
                        }
                        msgBuffer.append("读块5、6数据").append("\r\n");
                        handler.sendEmptyMessage(0);
                        bytes = iso15693Card.ReadMultiple((byte) 5, (byte)2);
                        msgBuffer.append("块5、6数据：").append(StringTool.byteHexToSting(bytes)).append("\r\n");
                        handler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
        }
        return true;
    }

}
